package cn.xu.tool.big.a.compments;

/**
 * 类名: StockDataFetcher
 * 描述: TODO
 * 作者: ClarkXu clark2021@qq.com
 * 日期: 2025/7/8
 */
import cn.xu.tool.big.a.dto.KLine;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class StockDataFetcher {
    // 根据股票代码和起止日期获取历史K线数据（日线）
    public static List<KLine> getStockData(String stockCode, String startDate, String endDate) throws Exception {
        //https://q.stock.sohu.com/hisHq?code=cn_002468&start=20250701&end=20250710
        String url = "https://q.stock.sohu.com/hisHq?code=" + stockCode + "&start=" + startDate + "&end=" + endDate + "&period=d&stat=1";
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet request = new HttpGet(url);
        List<KLine> kLines = new ArrayList<>();

        try (CloseableHttpResponse response = client.execute(request)) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity);
                // 解析JSON，搜狐API返回的是一个数组，数组里每个元素是一个对象，对象中有hq字段是数组，包含多天的数据
                JSONArray responseArray = new JSONArray(result);
                //[{"status":0,"hq":[["2025-07-07","22.08","22.16","0.13","0.59%","22.04","22.23","173316","38348.86","0.22%"],["2025-07-04","22.06","22.03","-0.04","-0.18%","21.97","22.15","173676","38316.64","0.22%"],["2025-07-03","22.11","22.07","-0.11","-0.50%","22.00","22.18","204020","45004.01","0.26%"],["2025-07-02","22.20","22.18","-0.03","-0.14%","22.06","22.27","166821","36952.41","0.21%"],["2025-07-01","22.42","22.21","-0.20","-0.89%","22.18","22.43","208879","46501.45","0.26%"]],"code":"cn_600406"}]
                // 遍历每个数组元素（通常只有一个元素）
                for (int i = 0; i < responseArray.length(); i++) {
                    JSONObject jsonObject = responseArray.getJSONObject(i);
                    JSONArray hqArray = jsonObject.getJSONArray("hq");
                    for (int j = 0; j < hqArray.length(); j++) {
                        JSONArray dayData = hqArray.getJSONArray(j);
                        // 每个dayData数组：日期、开盘价、收盘价、涨跌额、涨幅、最低价、最高价、成交量、成交金额
                        // 示例: ["2020-01-02", "10.50", "10.60", "0.10", "0.95%", "10.40", "10.70", "1000000", "10600000"]
                        // 日期    开盘   收盘   涨跌额(相对昨日收盘) 涨跌幅度(相对昨日收盘)  最低价 最高价 成交量  成交额(万) 换手
//                        ["2025-07-07","22.08","22.16","0.13","0.59%","22.04","22.23","173316","38348.86","0.22%"]
                        KLine kLine = new KLine();
                        kLine.setDate(dayData.getString(0)); // 注意：这里日期格式是yyyy-MM-dd，需要转换
                        kLine.setOpen(Double.parseDouble(dayData.getString(1)));
                        kLine.setClose(Double.parseDouble(dayData.getString(2)));
                        kLine.setHigh(Double.parseDouble(dayData.getString(6)));
                        kLine.setLow(Double.parseDouble(dayData.getString(5)));
                        kLine.setVolume(Long.parseLong(dayData.getString(7).replace(",", ""))); // 可能有逗号分隔
                        kLine.setAmount(Double.parseDouble(dayData.getString(8)));
                        kLine.setExchange(Double.parseDouble(dayData.getString(9).replace("%", ""))/100);
                        kLine.setAdd(Double.parseDouble(dayData.getString(3)));
                        kLine.setAddPercent(Double.parseDouble(dayData.getString(4).replace("%", ""))/100);
                        kLines.add(kLine);
                    }
                }
            }
        }

        // 按日期顺序（搜狐返回的是倒序，所以需要反转）
        List<KLine> sortedList = new ArrayList<>();
        for (int i = kLines.size() - 1; i >= 0; i--) {
            sortedList.add(kLines.get(i));
        }
        return sortedList;
    }

}
